package com.fanben100.gui;

import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import com.fanben100.biz.LogoutState;
import com.fanben100.biz.RegistContext;
import com.fanben100.biz.RequestBuilder;
import com.fanben100.domain.FormData;
import com.fanben100.domain.LoginModel;
import com.fanben100.domain.SysConfig;
import com.fanben100.util.DateUtil;
import com.fanben100.util.NumberUtil;
import com.fanben100.util.ProtocalUtil;
import com.fanben100.util.StringUtil;

public class TerminalFrame extends JFrame {

	private int operCount = 0;
	private double operSum = 0;

	JLabel tradeCountContentLabel = new JLabel();
	JLabel tradeSumContentLabel = new JLabel();
	JPopupMenu clearPopupMenu = new JPopupMenu();
	JMenuItem clearMenuItem = new JMenuItem("清除信息");

	Image icon = Toolkit.getDefaultToolkit().createImage(
			this.getClass().getResource("/img/logo.gif"));

	private static class TerminalFrameSingleHolder {
		private static final TerminalFrame instance = new TerminalFrame();
	}

	public static TerminalFrame getPosFrame() {
		return TerminalFrameSingleHolder.instance;
	}

	public static void openPosFrame() {
		TerminalFrame instance = TerminalFrameSingleHolder.instance;
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

		// 全屏
		// frame.setUndecorated(true);// 禁用frame的装饰,即没有标题栏等
		Toolkit tk = Toolkit.getDefaultToolkit();
		//Dimension di = tk.getScreenSize();
		// instance.setSize(di);
		// 居中定位
		Dimension frameSize = instance.getSize();
		if (frameSize.height > screenSize.height) {
			frameSize.height = screenSize.height;
		}
		if (frameSize.width > screenSize.width) {
			frameSize.width = screenSize.width;
		}
		instance.setLocation((screenSize.width - frameSize.width) / 2,
				(screenSize.height - frameSize.height) / 2);

		instance.getContentPane().setVisible(false);
		instance.validate();
		// instance.pack();
		instance.setVisible(true);
		RegistContext.getInstance().checkRegist(TerminalFrame.getPosFrame());
	}

	/**
	 * 当前操作员
	 */
	private LoginModel connectOperater = null;

	/**
	 * 当前是否为提交中
	 */
	private Boolean submitting = false;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final int TERMINAL_WIDTH = 960;
	private final int TERMINAL_HEIGHT = 700;
	private final String TERMINAL_TITLE = "fanben100超市终端";

	Font normalFont = new Font("宋体", Font.BOLD, 20);
	Font errorFont = new Font("宋体", Font.BOLD, 18);
	Font expenditureFont = new Font("宋体", Font.BOLD, 18);

	JMenuBar menuBar = new JMenuBar();
	JMenu systemMenu = new JMenu();
	JMenu helpMenu = new JMenu();
	JMenu cardMenu = new JMenu();
	JMenu exitMenu = new JMenu();

	public LoginModel getConnectOperater() {
		return connectOperater;
	}

	public void setConnectOperater(LoginModel connOper) {
		this.connectOperater = connOper;
	}

	JMenuItem systemMenu_regist = new JMenuItem();
	JMenuItem systemMenu_login = new JMenuItem();

	JMenuItem cardMenu_open = new JMenuItem();
	// JMenuItem cardMenu_manage = new JMenuItem();

	JMenuItem exitMenu_logon = new JMenuItem();
	JMenuItem exitMenu_exitManage = new JMenuItem();
	JMenuItem helpMenu_help = new JMenuItem();
	JMenuItem helpMenu_aboutAuthor = new JMenuItem();
	Icon terminalBackIcon = new ImageIcon("img\\WindowBackground.gif");//
	Border loweredbevel = BorderFactory.createEtchedBorder();
	// Border blackline = BorderFactory.createLineBorder(Color.black);

	JLabel labOperaterContent = new JLabel("", JLabel.LEFT);
	JLabel labCustomerNameContent = new JLabel("", JLabel.LEFT);

	// 商家名称
	JLabel labSellerNameContent = new JLabel("", JLabel.LEFT);
	// 商家编号
	JLabel labSellerNoContent = new JLabel("", JLabel.LEFT);

	// 消费总金额
	JTextField txtExpenditure = new JTextField("", 10);

	// 历史信息TabPanel
	JTabbedPane historyTabpanel = new JTabbedPane();

	// 历史交易信息Table
	String[] headers = { "会员卡号", "消费金额", "处理时间" };
	Object[][] cellData = null;
	DefaultTableModel defaultModel = new DefaultTableModel(cellData, headers) {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public boolean isCellEditable(int row, int column) {
			return false;
		}
	};
	JTable historyTable = new JTable(defaultModel);
	JScrollPane historyScrollPanel = new JScrollPane(historyTable);

	/**
	 * 其他信息面板
	 */
	JPanel otherInfoPanel = new JPanel();
	JLabel tradeCountLabel = new JLabel("交易笔数:");

	JLabel tradeSumLabel = new JLabel("交易总金额:");

	public JLabel getLabOperaterContent() {
		return labOperaterContent;
	}

	public void setLabOperaterContent(JLabel labOperaterContent) {
		this.labOperaterContent = labOperaterContent;
	}

	final JTextField txtCardNo = new JTextField();
	final JPasswordField txtPassword = new JPasswordField();

	private DefaultListModel resultModel = new DefaultListModel();
	private JList resultList = new JList(resultModel);

	private Toolkit toolkit = Toolkit.getDefaultToolkit();

	// 保存当前获得焦点组件
	private JComponent currentFocus = null;

	private TerminalFrame() {
		initSelfConfig();
		initCompoent();
	}

	private void initSelfConfig() {
		this.setTitle(TERMINAL_TITLE);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(new Dimension(TERMINAL_WIDTH, TERMINAL_HEIGHT));
		this.setIconImage(icon);
		toolkit.addAWTEventListener(new CapListener(), AWTEvent.KEY_EVENT_MASK);
		txtCardNo.addFocusListener(new FocusAdapter() {
			public void focusGained(FocusEvent e) {
				JComponent src = (JComponent) e.getSource();// 得到获得焦点的组件
				if (src instanceof JTextField) {
					currentFocus = src;
				}
			}

			public void focusLost(FocusEvent e) {
			}
		});
		txtPassword.addFocusListener(new FocusAdapter() {
			public void focusGained(FocusEvent e) {
				JComponent src = (JComponent) e.getSource();// 得到获得焦点的组件
				if (src instanceof JTextField) {
					currentFocus = src;
				}
			}

			public void focusLost(FocusEvent e) {
			}
		});
	}

	private void initCompoent() {
		this.setJMenuBar(menuBar);
		systemMenu.setMnemonic('S');
		systemMenu.setText("系统管理(S)");
		cardMenu.setText("会员办理(C)");
		cardMenu.setMnemonic('C');
		helpMenu.setMnemonic('H');
		helpMenu.setText("帮助(H)");
		exitMenu.setMnemonic('E');
		exitMenu.setText("退出(E)");
		systemMenu_regist.setMnemonic('A');
		systemMenu_regist.setText("商家注册(A)");
		systemMenu_regist
				.addActionListener(new TerminalFrame_systemMenu_regist_actionAdapter(
						this));
		systemMenu_login.setMnemonic('C');
		systemMenu_login.setText("系统登录(C)");
		systemMenu_login
				.addActionListener(new TerminalFrame_systemMenu_login_actionAdapter(
						this));
		cardMenu_open.setText("会员开卡(O)");
		cardMenu_open.setMnemonic('O');
		cardMenu_open
				.addActionListener(new Terminal_cardMenu_open_actionAdapter(
						this));

		// cardMenu_manage.setText("会员管理(M)");
		// cardMenu_manage.setMnemonic('M');

		exitMenu_logon.setMnemonic('L');
		exitMenu_logon.setText("注销(L)");
		exitMenu_logon
				.addActionListener(new TerminalFrame_exitMenu_loginout_actionAdapter(
						this));
		exitMenu_exitManage.setMnemonic('E');
		exitMenu_exitManage.setText("退出系统(E)");
		exitMenu_exitManage.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		helpMenu_help.setText("帮助(H)");
		helpMenu_help.setMnemonic('H');
		helpMenu_help.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(TerminalFrame.this,
						"请联系QQ:447378145");
			}
		});
		helpMenu_aboutAuthor.setMnemonic('A');
		helpMenu_aboutAuthor.setText("关于 (A)");
		helpMenu_aboutAuthor
				.addActionListener(new Terminal_helpMenu_about_actionAdapter(
						this));

		menuBar.add(systemMenu);
		// menuBar.add(cardMenu);
		menuBar.add(helpMenu);

		menuBar.add(exitMenu);
		systemMenu.add(systemMenu_regist);
		systemMenu.addSeparator();
		systemMenu.add(systemMenu_login);
		cardMenu.add(cardMenu_open);
		// cardMenu.add(cardMenu_manage);
		exitMenu.addSeparator();
		exitMenu.add(exitMenu_logon);
		exitMenu.addSeparator();
		exitMenu.add(exitMenu_exitManage);
		helpMenu.add(helpMenu_help);
		helpMenu.addSeparator();
		helpMenu.add(helpMenu_aboutAuthor);

		JLabel titleLabel = new JLabel();// ("返本100超市报单系统", JLabel.LEFT);
		ImageIcon titleIcon = new ImageIcon(this.getClass().getResource(
				"/img/logo.gif"));
		titleLabel.setIcon(titleIcon);
		titleLabel.setIconTextGap(SwingConstants.LEFT);
		titleLabel.setFont(new Font("宋体", Font.BOLD, 28));
		titleLabel.setForeground(Color.PINK);

		JPanel titlePanel = new JPanel();
		titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.X_AXIS));
		titlePanel.add(titleLabel);
		Surface titleSurface = new TitleSurface();
		titleSurface.setSize(new Dimension(200, 200));
		titlePanel.add(titleSurface);

		JPanel contentPanel = (JPanel) getContentPane();
		JLabel labCardNo = new JLabel("会员卡号:", JLabel.LEFT);
		labCardNo.setFont(normalFont);

		txtCardNo.setSize(new Dimension(20, 10));
		txtCardNo.setColumns(12);
		txtCardNo.setFont(normalFont);

		JLabel labPassword = new JLabel("会员密码:", JLabel.LEFT);
		labPassword.setFont(normalFont);

		txtPassword.setEchoChar('*');
		txtPassword.setSize(20, 20);
		txtPassword.setColumns(12);
		txtPassword.setFont(normalFont);
		SubmitAction action = new SubmitAction();
		txtPassword.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
				KeyStroke.getKeyStroke("F5"), action.getValue(Action.NAME));

		JLabel labSellerNo = new JLabel("商家编号:", JLabel.LEFT);
		labSellerNo.setFont(normalFont);
		labSellerNoContent.setFont(normalFont);

		JLabel labSellerName = new JLabel("商家名称:", JLabel.LEFT);
		labSellerName.setFont(normalFont);
		labSellerNameContent.setFont(normalFont);

		txtCardNo.addKeyListener(new KeyListener() {

			public void keyTyped(KeyEvent e) {
			}

			public void keyReleased(KeyEvent e) {
			}

			public void keyPressed(KeyEvent e) {
				int keyCode = e.getKeyCode();
				if (keyCode == KeyEvent.VK_ENTER) {
					if (txtCardNo.getText().length() == 0) {
						return;
					}
					txtPassword.grabFocus();
				}
			}
		});

		txtPassword.addActionListener(new SubmitAction());

		JPanel mainPanel = new JPanel();
		mainPanel.setBorder(loweredbevel);
		mainPanel.setLayout(new GridBagLayout());

		/**
		 * 商家面板
		 */
		JPanel sellerPanel = new JPanel();
		sellerPanel.add(labSellerNo);
		sellerPanel.add(labSellerNoContent);
		sellerPanel.add(labSellerName);
		sellerPanel.add(labSellerNameContent);
		sellerPanel.setBorder(loweredbevel);

		/**
		 * 消费金额面板
		 */
		JLabel labExpenditure = new JLabel("消费金额:", JLabel.LEFT);
		labExpenditure.setFont(normalFont);

		txtExpenditure.setForeground(Color.BLUE);
		txtExpenditure.setFont(normalFont);
		txtExpenditure.setSize(new Dimension(10, 10));
		txtExpenditure.setColumns(12);
		txtExpenditure.setDocument(new NumberLimitedDmt(10));

		JPanel expenditureP = new JPanel();
		expenditureP.add(labExpenditure);
		expenditureP.add(txtExpenditure);

		/**
		 * 会员及消费面板
		 */
		JPanel cardNoP = new JPanel();
		JPanel cardPasswordP = new JPanel();

		JPanel vipPanel = new JPanel();
		vipPanel.setLayout(new BoxLayout(vipPanel, BoxLayout.Y_AXIS));
		cardNoP.add(labCardNo);
		cardNoP.add(txtCardNo);
		cardPasswordP.add(labPassword);
		cardPasswordP.add(txtPassword);
		vipPanel.add(expenditureP);
		// vipPanel.add(labCardNo);
		// vipPanel.add(txtCardNo);
		// vipPanel.add(labPassword);
		// vipPanel.add(txtPassword);
		vipPanel.add(cardNoP);
		vipPanel.add(cardPasswordP);

		vipPanel.setBorder(loweredbevel);

		/**
		 * 当前登录操作员和会员信息显示面板
		 */
		JLabel labOperater = new JLabel("  操作员:", JLabel.LEFT);
		labOperater.setFont(normalFont);
		labOperaterContent.setFont(normalFont);
		JLabel labCustomerName = new JLabel("会员姓名:", JLabel.LEFT);
		labCustomerName.setFont(normalFont);
		labCustomerNameContent.setFont(normalFont);

		JPanel infoPanel = new JPanel();
		infoPanel.setLayout(new GridLayout(2, 2));
		infoPanel.add(labOperater);
		infoPanel.add(labOperaterContent);
		infoPanel.add(labCustomerName);
		infoPanel.add(labCustomerNameContent);
		infoPanel.setBorder(loweredbevel);

		txtExpenditure.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (txtExpenditure.getText().length() != 0) {
					txtCardNo.grabFocus();
					return;
					// submitForm();
				}
			}
		});

		// resultList.setSize(new Dimension(200,100));
		// resultList.setPreferredSize(new Dimension(150, 150));
		// expenditurePanel.add(expenditureP, BorderLayout.PAGE_START);
		JPanel expenditurePanel = new JPanel();
		expenditurePanel.setBorder(loweredbevel);
		expenditurePanel.setLayout(new BorderLayout());
		resultList.setCellRenderer(new MyCellRenderer());
		clearMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				resultModel.clear();
			}
		});
		clearPopupMenu.add(clearMenuItem);
		resultList.add(clearPopupMenu);
		resultList.addMouseListener(new ClearListListener());
		JScrollPane resultListPanel = new JScrollPane(resultList);
		expenditurePanel.add(resultListPanel, BorderLayout.CENTER);

		/**
		 * 帮助面板
		 */
		historyTabpanel.setSize(new Dimension(300, 200));

		JPanel recordPanel = new JPanel();

		JPanel helpPanel = new JPanel();
		helpPanel.setLayout(new BoxLayout(helpPanel, BoxLayout.Y_AXIS));
		helpPanel.setBorder(loweredbevel);
		JLabel f6Label = new JLabel("   F6\t设置光标", JLabel.CENTER);
		f6Label.setSize(120, 120);
		JLabel f8Label = new JLabel("   F8\t删除", JLabel.CENTER);
		JLabel f12Label = new JLabel("   F12\t 退出", JLabel.CENTER);
		JLabel submitLabel = new JLabel("   Enter\t提交", JLabel.CENTER);

		// JButton dispalyBtn = new JButton("显示10条");
		// JButton preBtn = new JButton("向前10条");
		// JButton nextBtn = new JButton("向后10条");

		// 分页按钮
		// JPanel btnPanel = new JPanel();
		// btnPanel.add(dispalyBtn);
		// btnPanel.add(preBtn);
		// btnPanel.add(nextBtn);

		// 分页mainpanel
		JPanel historyPanel = new JPanel();
		historyPanel.setLayout(new BorderLayout());

		// 设置列不可随容器组件大小变化自动调整宽度.
		// historyTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		// 设置行可选
		historyTable.setCellSelectionEnabled(true);
		// historyScrollPanel.setSize(new Dimension(300, 280));
		// historyPanel.setSize(new Dimension(300, 280));
		// historyTable.setSize(new Dimension(300, 280));
		// 控制会员卡号列（第一列）列宽
		TableColumn cardNoColumn = historyTable.getColumnModel().getColumn(0);
		cardNoColumn.setPreferredWidth(80);
		cardNoColumn.setMaxWidth(80);
		cardNoColumn.setMinWidth(80);
		TableColumn timeColumn = historyTable.getColumnModel().getColumn(2);
		timeColumn.setPreferredWidth(120);
		timeColumn.setMaxWidth(120);
		timeColumn.setMinWidth(120);
		// 设置复制粘贴适配器
		new ExcelAdapter(historyTable);

		historyPanel.add(historyScrollPanel, BorderLayout.CENTER);
		// historyPanel.add(btnPanel, BorderLayout.SOUTH);

		String name = "交易历史";
		historyTabpanel.add(name, historyPanel);
		name = "统计信息";
		otherInfoPanel
				.setLayout(new BoxLayout(otherInfoPanel, BoxLayout.Y_AXIS));
		Box tradeCountBox = Box.createHorizontalBox();
		tradeCountBox.setAlignmentX(Component.LEFT_ALIGNMENT);
		tradeCountBox.add(tradeCountLabel);
		tradeCountBox.add(tradeCountContentLabel);

		Box tradeSumBox = Box.createHorizontalBox();
		tradeSumBox.setAlignmentX(Component.LEFT_ALIGNMENT);
		tradeSumBox.add(tradeSumLabel);
		tradeSumBox.add(tradeSumContentLabel);

		otherInfoPanel.add(Box.createRigidArea(new Dimension(10, 10)));
		otherInfoPanel.add(tradeCountBox);
		otherInfoPanel.add(tradeSumBox);
		historyTabpanel.add(name, otherInfoPanel);

		helpPanel.add(f6Label);
		helpPanel.add(f8Label);
		helpPanel.add(f12Label);
		helpPanel.add(submitLabel);

		recordPanel.setLayout(new BorderLayout());
		recordPanel.add(helpPanel, BorderLayout.PAGE_START);
		recordPanel.add(historyTabpanel, BorderLayout.CENTER);

		GridBagConstraints c = new GridBagConstraints();

		c.gridx = 0; // 0行0列
		c.gridy = 0;
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.gridheight = 1;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.weightx = 1;
		c.weighty = 0;
		mainPanel.add(sellerPanel, c);

		c.gridx = 0;
		c.gridy = 1;
		c.weightx = 0.8;
		c.weighty = 0;
		c.gridwidth = 1;
		c.gridheight = 1;
		c.fill = GridBagConstraints.BOTH;
		c.insets = new Insets(5, 0, 0, 0);
		mainPanel.add(vipPanel, c);

		c.gridx = 1;
		c.gridy = 1;
		c.gridwidth = 1;
		c.gridheight = 1;
		c.weightx = 0.2;
		c.weighty = 0;
		c.insets = new Insets(5, 0, 0, 0);
		c.fill = GridBagConstraints.BOTH;
		mainPanel.add(infoPanel, c);

		c.gridx = 0;
		c.gridy = 2;
		c.gridwidth = 1;
		c.gridheight = 1;
		c.weightx = 0.8;
		c.weighty = 1;
		mainPanel.add(expenditurePanel, c);

		c.gridx = 1;
		c.gridy = 2;
		c.gridwidth = 1;
		c.gridheight = 1;
		c.weightx = 0.2;
		c.weighty = 1;
		mainPanel.add(recordPanel, c);

		contentPanel.setLayout(new BorderLayout());
		contentPanel.add(titlePanel, BorderLayout.PAGE_START);
		contentPanel.add(mainPanel, BorderLayout.CENTER);
		contentPanel.add(new StatusBar(), BorderLayout.SOUTH);
	}

	// private void validCardCustomer(Card card) {
	// // if (StringUtil.isNullOrEmpty(labOperaterContent.getText())) {
	// if (RegistContext.getInstance().getSysState() == null
	// || !(RegistContext.getInstance().getSysState() instanceof LogonState)) {
	// JOptionPane.showMessageDialog(this, "当前没有操作员登录终端", "提醒",
	// JOptionPane.ERROR_MESSAGE);
	// return;
	// }
	// // }
	// LoginModel customerModel = new Customer();
	// customerModel.setLoginId(txtCardNo.getText());
	// customerModel.setLoginPassword(txtPassword.getText());
	//
	// ValidLoginModel validModel = LoginTemplateFactory.getLoginTemplate(
	// customerModel).directLogin(customerModel);
	//
	// if (validModel.isValid()) {
	// labCustomerNameContent.setText(String.valueOf(validModel
	// .getLoginId()));
	// txtExpenditure.grabFocus();
	// rightConsole(null);
	// } else {
	// errorConsole("会员卡验证失败,会员卡号:" + txtCardNo.getText() + " "
	// + DateUtil.getCurrentDate());
	// }
	// }

	public JTextField getTxtExpenditure() {
		return txtExpenditure;
	}

	public JLabel getLabCustomerNameContent() {
		return labCustomerNameContent;
	}

	public JLabel getLabSellerNameContent() {
		return labSellerNameContent;
	}

	public JLabel getLabSellerNoContent() {
		return labSellerNoContent;
	}

	/**
	 * 商户注测
	 * 
	 * @author CYC
	 * 
	 */
	public void sysMenu_regist_actionPerformed(ActionEvent e) {
		SellerRegistDialog registDialog = new SellerRegistDialog(this, "商家注册",
				true);
		registDialog.setVisible(true);
	}

	class TerminalFrame_systemMenu_regist_actionAdapter implements
			ActionListener {
		private TerminalFrame adaptee;

		TerminalFrame_systemMenu_regist_actionAdapter(TerminalFrame adaptee) {
			this.adaptee = adaptee;
		}

		public void actionPerformed(ActionEvent actionEvent) {
			adaptee.sysMenu_regist_actionPerformed(actionEvent);
		}
	}

	/**
	 * 用户登录
	 */
	private void sysMenu_login_actionPerformed(ActionEvent e) {
		JDialog userLoginDialog = new UserLoginDialog(this, true);
		userLoginDialog.setVisible(true);
	}

	class TerminalFrame_systemMenu_login_actionAdapter implements
			ActionListener {
		private TerminalFrame adaptee;

		TerminalFrame_systemMenu_login_actionAdapter(TerminalFrame adaptee) {
			this.adaptee = adaptee;
		}

		public void actionPerformed(ActionEvent actionEvent) {
			adaptee.sysMenu_login_actionPerformed(actionEvent);
		}
	}

	/**
	 * 用户注销
	 */
	private void exitMenu_logout_actionPerformed(ActionEvent e) {
		RegistContext.getInstance().setSysState(new LogoutState(), this);
	}

	class TerminalFrame_exitMenu_loginout_actionAdapter implements
			ActionListener {
		private TerminalFrame adaptee;

		TerminalFrame_exitMenu_loginout_actionAdapter(TerminalFrame adaptee) {
			this.adaptee = adaptee;
		}

		public void actionPerformed(ActionEvent actionEvent) {
			adaptee.exitMenu_logout_actionPerformed(actionEvent);
		}
	}

	/**
	 * 会员开卡
	 * 
	 * @author Administrator
	 * 
	 */
	private void cardMenu_open_actionPerformed(ActionEvent e) {
		OpenCardDialog2 openCardDialog = new OpenCardDialog2(this, "会员开卡", true);
		openCardDialog.setVisible(true);
	}

	class Terminal_cardMenu_open_actionAdapter implements ActionListener {
		private TerminalFrame adaptee;

		Terminal_cardMenu_open_actionAdapter(TerminalFrame adaptee) {
			this.adaptee = adaptee;
		}

		public void actionPerformed(ActionEvent actionEvent) {
			adaptee.cardMenu_open_actionPerformed(actionEvent);
		}
	}

	/**
	 * 会员开卡
	 * 
	 * @author Administrator
	 * 
	 */
	private void helpMenu_about_actionPerformed(ActionEvent e) {
		CopyrightDialog dialog = new CopyrightDialog(this, true);
		dialog.setVisible(true);
	}

	class Terminal_helpMenu_about_actionAdapter implements ActionListener {
		private TerminalFrame adaptee;

		Terminal_helpMenu_about_actionAdapter(TerminalFrame adaptee) {
			this.adaptee = adaptee;
		}

		public void actionPerformed(ActionEvent actionEvent) {
			adaptee.helpMenu_about_actionPerformed(actionEvent);
		}
	}

	/**
	 * 功能键监听器
	 * 
	 * @author CYC
	 * 
	 */
	class CapListener implements AWTEventListener {
		public void eventDispatched(AWTEvent event) {
			if (event instanceof KeyEvent) {
				if (((KeyEvent) event).getKeyCode() == KeyEvent.VK_F6) {
					txtExpenditure.dispatchEvent(new FocusEvent(txtCardNo,
							FocusEvent.FOCUS_GAINED, true));
					txtExpenditure.requestFocusInWindow();
				} else if (((KeyEvent) event).getKeyCode() == KeyEvent.VK_F8) {
					if (currentFocus != null
							&& currentFocus instanceof JTextField) {
						((JTextField) currentFocus).setText(null);
					}
				} else if (((KeyEvent) event).getKeyCode() == KeyEvent.VK_F12) {
					System.exit(0);
				} else if (((KeyEvent) event).getKeyCode() == KeyEvent.VK_F2) {
					clearPopupMenu.show(resultList,
							(resultList.getWidth() - clearPopupMenu.WIDTH) / 2,
							(resultList.getHeight() - clearPopupMenu
									.getHeight()) / 2);
				}
			}
		}
	}

	/**
	 * 验证报单
	 */
	private FormData validForm() {
		if (txtCardNo.getText().length() < 4) {
			errorConsole("会员卡号格式不正确");
			return null;
		} else if (txtPassword.getPassword().length != 6) {
			errorConsole("密码输入位数不正确");
			return null;
		} else if (!NumberUtil.isNumeric(txtExpenditure.getText())) {
			errorConsole("消费金额输入不正确");
			return null;
		} else if (NumberUtil.formatDouble(txtExpenditure.getText()) <= 0) {
			errorConsole("消费金额必须为大于零");
			return null;
		}
		if (StringUtil.isNullOrEmpty(labOperaterContent.getText())) {
			errorConsole("不能获取当前操作员信息");
			return null;
		}
		FormData formData = FormData.getInstance(SysConfig.sellerLoginModel);
		// TODO cardno or loginid
		formData.setCustomerId(txtCardNo.getText());
		formData.setCustomerPassword(new String(txtPassword.getPassword()));

		formData.setExpenditureMoney(Double.valueOf(txtExpenditure.getText()));
		formData.setOperater(connectOperater.getLoginId());
		return formData;
	}

	/**
	 * 提交报单
	 */
	private synchronized boolean submitForm() {
		submitting = true;
		FormData formData = validForm();
		String submitResult = "";
		if (formData != null) {
			// TODO 此处访问地址需要更改
			RequestBuilder requestBuilder = new RequestBuilder(
					"http://www.fanben100.net/shop.php");
			requestBuilder.build("class", "super");
			requestBuilder.build("method", "do_form");
			requestBuilder.build("super_id", formData.getSellerId().toString());
			// requestBuilder.build("sellerPassword",
			// formData.getSellerPassword()
			// .toString());
			requestBuilder.build("card_number", formData.getCustomerId()
					.toString());
			requestBuilder.build("card_password", formData
					.getCustomerPassword().toString());
			requestBuilder.build("sum", formData.getExpenditureMoney()
					.toString());
			requestBuilder.build("opp_name", formData.getOperater().toString());
			try {
				submitResult = StringUtil.trimAll(ProtocalUtil.httpRequest(
						new URL(requestBuilder.toString()), null));
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
				submitResult = "请求超时，请检查网络连通情况 " + DateUtil.getCurrentDate();
			}
			if ("操作成功".equals(submitResult)) {
				rightConsole("操作成功!会员卡号:" + txtCardNo.getText() + ",消费金额:"
						+ txtExpenditure.getText() + " " + " "
						+ DateUtil.getCurrentDate());
				addHistoryTableRecord(formData);
				submitting = false;
				resetForm();
				return true;
			} else {
				errorConsole(submitResult);
				submitting = false;
				return false;
			}
		}
		submitting = false;
		return false;
	}

	/**
	 * 提交Action
	 * 
	 * @author CYC
	 * 
	 */
	class SubmitAction extends AbstractAction implements Runnable {
		private static final long serialVersionUID = 1L;

		public SubmitAction() {
			super("报单Action");
		}

		public void actionPerformed(ActionEvent e) {
			synchronized (submitting) {
				if (!submitting) {
					Thread submitT = new Thread(this);
					submitT.start();
				}
			}
		}

		public void run() {
			submitForm();
		}
	}

	/**
	 * 正确输出控制台
	 * 
	 * @param text
	 */
	private void rightConsole(String text) {
		// resultModel.clear();
		if (!StringUtil.isNullOrEmpty(text)) {
			resultModel.addElement(text);
		}
		resultList.setForeground(Color.BLACK);
	}

	/**
	 * 错误输出控制台
	 * 
	 * @param text
	 */
	private void errorConsole(String text) {
		// resultModel.clear();
		if (!StringUtil.isNullOrEmpty(text)) {
			resultModel.addElement(text);
		}
		resultList.setForeground(Color.RED);
		resultList.setFont(errorFont);
	}

	/**
	 * 增加历史记录表格数据
	 */

	private void addHistoryTableRecord(FormData formData) {
		DefaultTableModel tableModel = (DefaultTableModel) historyTable
				.getModel();
		// tableModel.setRowCount(0);// 清除原有行

		// 填充数据
		String[] arr = new String[3];
		arr[0] = String.valueOf(Integer.valueOf(txtCardNo.getText()));
		arr[1] = String.valueOf(formData.getExpenditureMoney());
		arr[2] = DateUtil.getCurrentDate();

		// 添加数据到表格
		tableModel.addRow(arr);
		historyTable.invalidate();
		updateStatInfo(formData);
	}

	/**
	 * 更新统计信息
	 * 
	 * @param formData
	 */
	private void updateStatInfo(FormData formData) {
		this.operCount++;
		this.operSum += formData.getExpenditureMoney();
		this.tradeCountContentLabel.setText(String.valueOf(this.operCount));
		this.tradeSumContentLabel.setText(String.valueOf(this.operSum));
	}

	/**
	 * 重置
	 */
	private void resetForm() {
		txtExpenditure.setText(null);
		txtCardNo.setText(null);
		txtPassword.setText(null);
		txtExpenditure.grabFocus();
	}

	/**
	 * 重置
	 */
	public void resetContentPanel() {
		resetForm();
		this.resultModel.clear();
		this.tradeCountContentLabel.setText(null);
		this.tradeSumContentLabel.setText(null);
		((DefaultTableModel) historyTable.getModel()).getDataVector().clear();
		/* 通知所有侦听器，表的所有行单元格值可能已更改 */
		((DefaultTableModel) historyTable.getModel()).fireTableDataChanged();
	}

	// 5:实现鼠标监听器
	class ClearListListener extends MouseAdapter {
		// e.getButton() 返回值有 1，2，3。1代表鼠标左键，3代表鼠标右键
		// jList.getSelected() 返回的是选中的JList中的项数。
		// if语句的意思也就是，在JList 中点击了右键而且JList选中了某项，显示右键菜单
		// e.getX() , e.getY() 返回的是鼠标目前的位置！也就是在目前鼠标的位置上弹出右键
		public void mouseClicked(MouseEvent e) {
			if (e.getButton() == MouseEvent.BUTTON3) {
				clearPopupMenu.show(resultList, e.getX(), e.getY());
				// resultModel.clear();
			}
		}

	}
}
